﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using CodeTitans.JSon;

namespace MendeleyClient.Phone
{
    public class SearchDataBroker: DataBrokerBase
    {
        SearchViewModel searchViewModel;
        WebClient webClient;
        string uriStr = "http://api.mendeley.com/oapi/documents/search/";

        public SearchDataBroker(SearchViewModel searchViewModel)
        {
            this.searchViewModel = searchViewModel;
            webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
        }

        public void GetData(string term)
        {
            if (!webClient.IsBusy)
            {
                if (term.Length > 0)
                {
                    webClient.DownloadStringAsync(new Uri(uriStr + term + "/?" + this.consumerKeyStr));
                }
            }
        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                // If the request was not canceled and did not throw
                // an exception, display the resource.
                if (!e.Cancelled && e.Error == null)
                {
                    JSonReader reader = new JSonReader();
                    IJSonObject jsonObject = reader.ReadAsJSonObject(e.Result.ToString());
                    foreach (var record in jsonObject["documents"].ArrayItems)
                    {
                        string authors = "";
                        try
                        {
                            foreach (var author in record["authors"].ArrayItems)
                            {
                                authors += (author["forename"].StringValue + " " + author["surname"].StringValue + ", ");
                            }
                            authors = authors.Substring(0, authors.LastIndexOf(","));
                        }
                        catch { }

                        searchViewModel.Items.Add(new SearchItemViewModel()
                        {
                            Title = record["title"].StringValue,
                            Authors = authors,
                            Year = record["year"].StringValue,
                            Publication = record["publication_outlet"].StringValue,
                            Link = record["mendeley_url"].StringValue
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                /*
                200 OK: Success! This header is sent for GET requests together with a JSON object containing the data requested.
                201 Created: Another success header! This one is sent after a POST request has been successful.
                204 No Content:
                400 Bad Request: The request was invalid. An accompanying error message will explain why.
                401 Unauthorized: Authentication credentials were missing or incorrect.
                403 Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to rate limiting.
                404 Not Found: The URI requested is invalid or the resource requested doesn't exist.
                503 Service Unavailable: Mendeley is up, but something went wrong, please try again later.
                */
            }
        }

        private void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
        }
    }
}
